package com.itheima.filters;

import cn.hutool.core.lang.Chain;
import cn.hutool.core.util.StrUtil;
import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;

/**
 * @Author:篍
 * @Date: 2025/07/17 12:18
 * @Description:
 */
//@WebFilter("/*")
public class AuthorizedFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpServletRequest= (HttpServletRequest) servletRequest;
        HttpServletResponse httpServletResponse= (HttpServletResponse) servletResponse;
        //获取请求url
        String uri = httpServletRequest.getRequestURI();

        //判断是否是登录，是则直接放行
        if(uri.contains("/login")){
            filterChain.doFilter(servletRequest,servletResponse);
            System.out.println("我登陆啦");
            return;
        }
            //不是则获取token
            String token = httpServletRequest.getHeader("token");
            //token为空
            if (StrUtil.isBlank(token)){
                httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                return;
            }
                //不为空,校验token
                try {
                    Claims claims = JwtUtils.parseJWT(token);
                    Object id = claims.get("id");
                    System.out.println(id);
                    //放行
                    System.out.println("AuthorizedFilter");
                    filterChain.doFilter(servletRequest,servletResponse);
                    System.out.println("AuthorizedFilter");
                } catch (Exception e) {
                    //非法token
                    httpServletResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                }
    }
}
